package org.ipmsg.core;

import java.util.StringTokenizer;
import java.util.Vector;

/**
 *
 * @author Vangie
 */
public class Attachment
{

    private Vector fileVector;
    private Vector tmpVector;
    private String attachment;
    private String filepaths[];

    public Attachment(String attachment)
    {
        this.attachment = attachment;
        fileVector = new Vector();
        /**
         * attachment由两级分隔符"\007"和":"分隔
         * 其结构为
         * [...\007]FileId:FileName:FileSize:FileLastModified:FileAttribute[\007...]
         * 用StringTokenizer将其分割到二维Vector中
         */
        for(StringTokenizer fileTokenizer = new StringTokenizer(attachment, Protocol.FILELIST_SEPARATOR, false); fileTokenizer.hasMoreTokens(); fileVector.addElement(tmpVector))
        {
            StringTokenizer attributeTokenizer = new StringTokenizer(fileTokenizer.nextToken(), ":", false);
            //这里似乎是一个bug
            if(attributeTokenizer.countTokens() <= 1)
            {
                break;
            }
            tmpVector = new Vector();
            for(; attributeTokenizer.hasMoreTokens(); tmpVector.addElement(attributeTokenizer.nextToken())) { }
        }

    }

    public Attachment(String attachment, String path[])
    {
        this(attachment);
        filepaths = path;
    }

    public boolean hasFiles()
    {
        return !fileVector.isEmpty();
    }

    public int countFiles()
    {
        return fileVector.size();
    }

    public long getFileID(int i)
    {
        tmpVector = (Vector)fileVector.elementAt(i);
        return Long.parseLong(tmpVector.elementAt(0).toString());
    }

    public String getFileName(int i)
    {
        tmpVector = (Vector)fileVector.elementAt(i);
        return tmpVector.elementAt(1).toString();
    }

    public long getFileSize(int i)
    {
        tmpVector = (Vector)fileVector.elementAt(i);
        return Long.parseLong(tmpVector.elementAt(2).toString(), 16);
    }

    public long getFileLastModified(int i)
    {
        tmpVector = (Vector)fileVector.elementAt(i);
        long t = Long.parseLong(tmpVector.elementAt(3).toString(), 16);
        return t * 1000L;
    }

    public long getFileAttribute(int i)
    {
        tmpVector = (Vector)fileVector.elementAt(i);
        return Long.parseLong(tmpVector.elementAt(4).toString(), 16);
    }

    public String getFilePath(int i)
    {
        return filepaths[i];
    }

    public String getStringAttachment()
    {
        return attachment;
    }

    @Override
    public String toString()
    {
        return (new StringBuilder("[")).append(attachment).append("]").toString();
    }
}
